package com.pig4cloud.pig.common.security.util;


import com.pig4cloud.pig.common.security.service.PigUser;
import lombok.experimental.UtilityClass;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

import java.util.List;
import java.util.stream.Collectors;

import static cn.hutool.core.util.NumberUtil.binaryToInt;
import static cn.hutool.core.util.StrUtil.removePrefix;
import static cn.hutool.core.util.StrUtil.startWith;
import static com.pig4cloud.pig.common.core.constant.SecurityConstants.ROLE;

/**
 * 安全工具类
 *
 * @author L.cm
 */
@UtilityClass
public class SecurityUtils {
    /**
     * 获取Authentication
     */
    public Authentication getAuthentication() {
        return SecurityContextHolder.getContext().getAuthentication();
    }

    /**
     * 获取用户
     *
     * @param authentication
     * @return PigxUser
     * <p>
     */
    public PigUser getUser(Authentication authentication) {
        return authentication.getPrincipal() instanceof PigUser ?
                (PigUser) authentication.getPrincipal() : null;
    }

    /**
     * 获取用户
     */
    public PigUser getUser() {
        return getUser(getAuthentication());
    }

    /**
     * 获取用户角色信息
     *
     * @return 角色集合
     */
    public List<Integer> getRoles() {

        List<Integer> roleIds = getAuthentication().getAuthorities().parallelStream()
                .filter(granted -> startWith(granted.getAuthority(), ROLE))
                .map(granted -> binaryToInt(removePrefix(granted.getAuthority(), ROLE)))
                .collect(Collectors.toList());

        return roleIds;
    }

}
